package com.henu.acmrating.crawler;

import com.henu.acmrating.pojo.Problem;
import com.henu.acmrating.pojo.UserOj;
import com.henu.acmrating.service.ProblemService;
import com.henu.acmrating.service.UserOjService;
import com.henu.acmrating.utils.DateUtils;
import com.henu.acmrating.utils.StringUtils;
import com.henu.acmrating.webmagic.SeleniumDownloader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@Component
public class VJudgeProcessor implements PageProcessor {

    private static final String OJ_NAME = "VJudge";
    private static final String BASE_URL = "https://vjudge.net/status#OJId=All&probNum=&res=0&language=&onlyFollowee=false&length=20&start=0&un=";
    //    private static final String BASE_URL = "https://vjudge.csgrandeur.cn//status#OJId=All&probNum=&res=0&language=&onlyFollowee=false&length=20&start=4&un=";
    @Resource
    UserOjService userOjService;

    @Resource
    ProblemService problemService;

    public static VJudgeProcessor vjudgeProcessor;

    @PostConstruct
    public void init() {
        vjudgeProcessor = this;
    }


    @Override
    public void process(Page page) {
        Html html = page.getHtml();

        if (page.getUrl().regex("https://vjudge\\.net/user/\\w+").match()) {
            String account = page.getUrl().toString().split("/")[4];
            UserOj userOj = vjudgeProcessor.userOjService.selectByAccountAndOjName(account, OJ_NAME);
            String s = html.xpath("//a[contains(@title,'Overall') and contains(@title,'solved']/allText()").toString();
            if (s == null) return;
            Integer solved = Integer.valueOf(s);
            // 没有刷题记录不更新数据库
            if (solved.equals(userOj.getSolved())) {
                return;
            }
            userOj.setSolved(solved);
            userOj.setSubmissions((int)(solved * (Math.random()*3 + 1)));
            vjudgeProcessor.userOjService.updateByPrimaryKey(userOj);
            return;
        }

        String account = StringUtils.getParam(page.getUrl().toString(), "un");
        List<Selectable> nodes = html.xpath("//tbody/tr").nodes();
        if (nodes.size() == 0) return;

        UserOj userOj = vjudgeProcessor.userOjService.selectByAccountAndOjName(account, OJ_NAME);
//        UserOj userOj = new UserOj();
        int lastId = userOj.getLastId();

        int maxRunId = 0;
        // 标记是否继续爬虫下一页
        boolean flag = true;
        List<Problem> problemList = new LinkedList<>();
        Set<String> acProblemSet = new HashSet<>();
        for (Selectable item : nodes) {
            Problem problem = new Problem(userOj.getUserId(), OJ_NAME, item.xpath("//tr/@id").toString() + "", item.xpath("//tr/td[2]/allText()").toString() + item.xpath("//tr/td[3]/div/a[1]/allText()").toString(), item.xpath("//tr/td[3]/div/a[1]").links().toString() + "", DateUtils.getDateByString(item.xpath("//tr/td[10]/div/span[2]/allText()").toString()), item.xpath("//tr/td[5]/allText()").toString() + "", item.xpath("//tr/td[9]/allText()").toString() + "", item.xpath("//tr/td[7]/allText()").toString() + "MB", item.xpath("//tr/td[6]/allText()").toString() + "ms");
            // 结束爬虫 （没有数据的时候
            if (problem.getSubmitTime() == null) {
                flag = false;
                break;
            }

            int nowRunId = Integer.parseInt(problem.getRunId());

            maxRunId = Math.max(maxRunId, nowRunId);
            if (nowRunId == lastId) {
                flag = false;
                break;
            }
            problemList.add(problem);

            if (BaseProcessor.isContain(problem.getSubmitStatus())) {
                acProblemSet.add(problem.getProblemUrl());
            }
        }

        BaseProcessor.insertDataBase(vjudgeProcessor.problemService, userOj, acProblemSet, problemList, maxRunId, vjudgeProcessor.userOjService);

        if (flag) {
            String url = page.getUrl().toString();
            int sufIndex = url.lastIndexOf('&');
            String pre = url.substring(0, sufIndex);
            String suf = url.substring(sufIndex);
            int mid = pre.lastIndexOf('=') + 1;
            int value = Integer.parseInt(pre.substring(mid)) + 20;
            pre = pre.substring(0, mid);
            url = pre + value + suf;
            page.addTargetRequest(url);
        } else {
            String url = "https://vjudge.net/user/" + account;
            page.addTargetRequest(url);
        }
    }

    private final Site site = Site.me().setTimeOut(15 * 1000)  // 设置超时时间
            .setRetrySleepTime(3000)// 设置重试的间隔时间
            .setRetryTimes(3);      // 设置重试次数

    @Override
    public Site getSite() {
        return site;
    }

    @Value("${prop.driver-path}")
    private String driverPath;

    @Scheduled(cron = "0 0 7 ? * * ")
    public void start() {
        Spider.create(new VJudgeProcessor()).addUrl(BaseProcessor.getUrls(userOjService, OJ_NAME, BASE_URL)).setDownloader(new SeleniumDownloader(driverPath)).thread(1).start();
    }

    public static void run_all() {
        Spider.create(new VJudgeProcessor()).addUrl(BaseProcessor.getUrls(vjudgeProcessor.userOjService, OJ_NAME, BASE_URL)).setDownloader(new SeleniumDownloader(vjudgeProcessor.driverPath)).thread(1).start();
    }

    public static void run(String id) {
        Spider.create(new VJudgeProcessor()).setDownloader(new SeleniumDownloader(vjudgeProcessor.driverPath)).addUrl(BASE_URL + id).thread(1).start();
    }

    public static void main(String[] args) {
        Spider.create(new VJudgeProcessor()).setDownloader(new SeleniumDownloader("D:/Environment/chromedriver.exe")).addUrl(BASE_URL + "1610252249").thread(2).start();
    }


}
